package com.xindaoapp.happypet.fragments;

import java.util.Map;

import android.animation.ObjectAnimator;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindao.photonics.fragments.manager.BaseFragment;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.activity.PrivateLetterActivity;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.BaseEntity;
import com.xindaoapp.happypet.bean.User;
import com.xindaoapp.happypet.protocol.MoccaApi;
import com.xindaoapp.happypet.utils.CommonParameter;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.view.CircleImageView;
import com.xindaoapp.happypet.viewpager.SwitchTabViewPager;
import com.xindaoapp.happypet.viewpager.ViewPagerAdapter;
import com.xindaoapp.happypet.viewpager.ViewPagerWindow;
import com.xindaoapp.happypet.viewpager.windows.UserMyAttentionWindow;
import com.xindaoapp.happypet.viewpager.windows.UserMyLoveWindow;
import com.xindaoapp.happypet.viewpager.windows.UserMyPostWindow;

/**
 * 用户信息界面
 * 
 * @author chenghao
 * 
 */
public class UserInfoFragment extends BaseFragment implements OnClickListener {
    private SwitchTabViewPager vViewPager;
    private ImageView vAttention;
    private View vManage;

    private User mFriendUserInfo;
    private String mFriendUid;
    private String mFriendUserName;
    private LoginSuccessReceiver mLoginSuccessReceiver;
    private ScrollReceiver mScrollReceiver;
    private View mView;

    private View r_top, layout_for_pop;
    private boolean isHasUp = false;
    private ImageView user_icon, back, sixin;
    private TextView user_name, fans_count, tv_jinyan, tv_fenghao;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_userinfo, container, false);
        return mView;
    }

    @Override
    protected void initViews(View view) {
        super.initViews(view);

        back = (ImageView) view.findViewById(R.id.back);
        sixin = (ImageView) view.findViewById(R.id.sixin);
        r_top = view.findViewById(R.id.r_top);
        layout_for_pop = view.findViewById(R.id.layout_for_pop);
        tv_jinyan = (TextView) view.findViewById(R.id.tv_jinyan);
        tv_fenghao = (TextView) view.findViewById(R.id.tv_fenghao);
        vAttention = (ImageView) view.findViewById(R.id.attention);
        vManage = view.findViewById(R.id.tv_manage);
        vManage.setOnClickListener(this);
        tv_jinyan.setOnClickListener(this);
        tv_fenghao.setOnClickListener(this);
        // TODO 禁掉版主全乡
        // vManage.setVisibility(View.GONE);
        if (UserState.getUser() == null) {
            vManage.setVisibility(View.GONE);
            // 测试,给版主加上
        } else if (UserState.getUser().adminid == 1 || UserState.getUser().adminid == 2) {
            vManage.setVisibility(View.VISIBLE);
        } else {
            vManage.setVisibility(View.GONE);
        }
        user_icon = (CircleImageView) getView().findViewById(R.id.user_icon);
        user_name = (TextView) getView().findViewById(R.id.user_name);
        fans_count = (TextView) getView().findViewById(R.id.fans_count);
        vViewPager = (SwitchTabViewPager) getView().findViewById(R.id.viewpager);

        mScrollReceiver = new ScrollReceiver();
        getActivity().registerReceiver(mScrollReceiver, new IntentFilter(Constants.SCROLL_FOR));
        mLoginSuccessReceiver = new LoginSuccessReceiver();
        getActivity().registerReceiver(mLoginSuccessReceiver,
                new IntentFilter(Constants.ACTION_LOGIN_STATE_CHANGED));
        mFriendUid = getArguments().getString(Constants.KEY_UID);
        mFriendUserName = getArguments().getString(Constants.KEY_USERNAME);
        // initTopBg(view);

        ImageLoader.getInstance().displayImage(getArguments().getString(Constants.KEY_USERFACE),
                user_icon);
        user_name.setText(mFriendUserName);
        vViewPager.addTabs(new View[] {getView().findViewById(R.id.tab_invitation),
                getView().findViewById(R.id.tab_attention), getView().findViewById(R.id.tab_fans)},
                0, true, false);
        ViewPagerWindow[] windows =
                new ViewPagerWindow[] {
                        new UserMyLoveWindow(getActivity(), getArguments().getString(
                                Constants.KEY_UID)),
                        new UserMyPostWindow(getActivity(), getArguments().getString(
                                Constants.KEY_UID)),
                        new UserMyAttentionWindow(getActivity(), getArguments().getString(
                                Constants.KEY_UID))};
        vViewPager.addPagerWindows(windows);
        vViewPager.setAdapter(new ViewPagerAdapter(windows));
        if (getArguments() != null) {
            vViewPager.setCurrentItem(getArguments().getInt(Constants.KEY_SKIP_TAB_INDEX));
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(mLoginSuccessReceiver);
        getActivity().unregisterReceiver(mScrollReceiver);
    }

    @Override
    protected void initEvents(View view) {
        super.initEvents(view);
        vAttention.setOnClickListener(this);
        back.setOnClickListener(this);
        sixin.setOnClickListener(this);
    }

    @Override
    protected void onLoadData() {
        super.onLoadData();
        vAttention.setEnabled(false);
        getMoccaApi().getUserInfoByUid(mFriendUid, new IRequest<Map<String, Object>>() {

            @Override
            public void request(Map<String, Object> t) {
                if (t != null && t.containsKey(MoccaApi.RESPONSE_USERINFO)) {
                    mFriendUserInfo = (User) t.get(MoccaApi.RESPONSE_USERINFO);
                    fans_count.setText(String.format("%s粉丝", mFriendUserInfo.fanscount));
                    vAttention.setEnabled(true);
                    handleAttentionViewState(mFriendUserInfo.follow);
                }
            }
        });
    }

    private void initTopBg(View view) {
        LayoutParams params =
                new LayoutParams(CommonParameter.sScreenWidth,
                        CommonParameter.sScreenWidth * 327 / 640);
        view.findViewById(R.id.r_top).setLayoutParams(params);
    }

    @Override
    protected boolean showBottomTabBar() {
        return false;
    }

    @Override
    protected boolean showTopTabBar() {
        return false;
    }

    @Override
    protected boolean showRightView() {
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.attention:
                if (UserState.isLogged(mActivity)) {
                    handleAttention();
                }
                break;
            case R.id.tv_manage:
                if (layout_for_pop.getVisibility() == View.VISIBLE) {
                    layout_for_pop.setVisibility(View.GONE);
                } else {
                    layout_for_pop.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.back:
                getActivity().finish();
                break;
            case R.id.tv_jinyan:
                layout_for_pop.setVisibility(View.GONE);
                if (UserState.isLogged(mActivity)) {
                    new AlertDialog.Builder(mActivity).setMessage("确定对该号禁言7天?").setTitle("提示")
                            .setNegativeButton("确定", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    goJinYan();
                                }
                            }).setPositiveButton("取消", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create().show();
                }
                break;
            case R.id.tv_fenghao:
                layout_for_pop.setVisibility(View.GONE);
                if (UserState.isLogged(mActivity)) {
                    new AlertDialog.Builder(getActivity()).setMessage("确定永久封除该号?").setTitle("提示")
                            .setNegativeButton("确定", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    goFengHao();

                                }
                            }).setPositiveButton("取消", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create().show();
                }
                break;
            case R.id.sixin:
                Intent i = new Intent(getActivity(), PrivateLetterActivity.class);
                i.putExtra(Constants.KEY_TOUID, mFriendUid);
                i.putExtra(Constants.KEY_USERNAME, mFriendUserName);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                getActivity().startActivity(i);
                break;
            default:
                break;
        }
    }

    private void goFengHao() {
        getMoccaApi().fengHaoOrJinYan(true, mFriendUid, new IRequest<BaseEntity>() {

            @Override
            public void request(BaseEntity t) {
                if (t != null) {
                    if (t.getResult().equals("0")) {
                        Toast.makeText(getActivity(), "封号成功", Toast.LENGTH_SHORT).show();
                        HappyPetApplication.mHandler.postDelayed(new Runnable() {

                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                                mActivity.finish();
                            }
                        }, 500);
                    } else {
                        Toast.makeText(getActivity(), t.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getActivity(), getResources().getString(R.string.net_error),
                            Toast.LENGTH_SHORT).show();
                }



            }
        });
    }

    private void goJinYan() {
        getMoccaApi().fengHaoOrJinYan(false, mFriendUid, new IRequest<BaseEntity>() {

            @Override
            public void request(BaseEntity t) {

                if (t != null) {
                    if (t.getResult().equals("0")) {
                        Toast.makeText(getActivity(), "禁言成功", Toast.LENGTH_SHORT).show();
                        HappyPetApplication.mHandler.postDelayed(new Runnable() {

                            @Override
                            public void run() {
                                // TODO Auto-generated method stub

                                mActivity.finish();
                            }
                        }, 500);
                    } else {
                        Toast.makeText(getActivity(), t.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getActivity(), getResources().getString(R.string.net_error),
                            Toast.LENGTH_SHORT).show();
                }

            }
        });

    }

    private void handleAttentionViewState(int follow) {
        if (mFriendUserInfo.follow == 0) {
            vAttention.setImageResource(R.drawable.follow);
        } else if (mFriendUserInfo.follow == 1) {
            vAttention.setImageResource(R.drawable.followed);
        }
    }

    private void handleAttention() {
        if (null == mFriendUserInfo) {
            return;
        }
        handleAttentionViewState(mFriendUserInfo.follow == 0 ? 1 : 0);
        vAttention.setEnabled(false);
        if (mFriendUserInfo.follow == 0) {
            getMoccaApi().addFollowAdd(mFriendUid, mFriendUserInfo.username,
                    new IRequest<Boolean>() {

                        @Override
                        public void request(Boolean t) {
                            mFriendUserInfo.follow = t ? 1 : 0;
                            vAttention.setEnabled(true);
                            handleAttentionViewState(mFriendUserInfo.follow);
                        }
                    });
        } else if (mFriendUserInfo.follow == 1) {
            getMoccaApi().deleteFollowAdd(mFriendUid, new IRequest<Boolean>() {

                @Override
                public void request(Boolean t) {
                    mFriendUserInfo.follow = t ? 0 : 1;
                    vAttention.setEnabled(true);
                    handleAttentionViewState(mFriendUserInfo.follow);
                }
            });
        }
    }

    class LoginSuccessReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            onLoadData();
        }

    }

    class ScrollReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            int flg = vViewPager.getCurrentItem();

            // 先禁掉
            // handleBroadcast(intent, flg);


        }

        private void handleBroadcast(Intent intent, int flg) {
            // TODO Auto-generated method stub

            if (intent.getStringExtra("from").equals(flg + "")) {


                if (intent.getStringExtra("go").equals("up") && !isHasUp) {
                    handleScroll(true);
                    isHasUp = true;
                } else if (intent.getStringExtra("go").equals("down") && isHasUp) {
                    handleScroll(false);
                    isHasUp = false;
                }
            }

        }
    }

    private void handleScroll(boolean i) {
        // TODO Auto-generated method stub

        if (Build.VERSION.SDK_INT >= 11 && i) {
            // 应用translationX动画
            // ObjectAnimator oa =
            // ObjectAnimator.ofFloat(mView, "translationY",
            // -CommonUtil.dip2px(mActivity, 145));

            // ObjectAnimator oa =
            // ObjectAnimator.ofFloat(r_top, "height", CommonUtil.dip2px(mActivity, 200),
            // CommonUtil.dip2px(mActivity, 150), CommonUtil.dip2px(mActivity, 50), 0);
            // oa.setInterpolator(new AccelerateInterpolator());
            // oa.setDuration(200);
            // oa.start();

            performAnimate(true, CommonUtil.dip2px(mActivity, 200),
                    CommonUtil.dip2px(mActivity, 55));


        } else if (Build.VERSION.SDK_INT >= 11) {
            // 应用translationX动画
            // ObjectAnimator oa =
            // ObjectAnimator.ofFloat(mView, "translationY", CommonUtil.dip2px(mActivity, 0));

            // ObjectAnimator oa =
            // ObjectAnimator.ofFloat(r_top, "height", 0, CommonUtil.dip2px(mActivity, 50),
            // CommonUtil.dip2px(mActivity, 150), CommonUtil.dip2px(mActivity, 200));
            // oa.setInterpolator(new AccelerateInterpolator());
            // oa.setDuration(200);
            // oa.start();

            performAnimate(false, CommonUtil.dip2px(mActivity, 55),
                    CommonUtil.dip2px(mActivity, 200));



        }

        // final TranslateAnimation animation =
        // new TranslateAnimation(0, 0, 0, -CommonUtil.dip2px(mActivity, 200));
        // animation.setDuration(2000);// 设置动画持续时间
        // animation.setRepeatCount(1);// 设置重复次数
        // // animation.setFillAfter(true);
        // animation.setRepeatMode(Animation.REVERSE);// 设置反方向执行
        // r_top.setAnimation(animation);
        // // r_top.setVisibility(View.GONE);
        // animation.startNow();


        // final TranslateAnimation animation = new TranslateAnimation(0, 150,0, 0);
        // animation.setDuration(2000);//设置动画持续时间
        // animation.setRepeatCount(2);//设置重复次数
        // animation.setRepeatMode(Animation.REVERSE);//设置反方向执行
        // start.setOnClickListener(new OnClickListener() {
        // public void onClick(View arg0) {
        // image.setAnimation(animation);
        // /** 开始动画 */
        // animation.startNow();
        // animation.setAnimationListener(new AnimationListener() {
        //
        // @Override
        // public void onAnimationEnd(Animation animation) {
        // // RelativeLayout.LayoutParams aLayoutParams = (RelativeLayout.LayoutParams)
        // // context.tab_front_bg
        // // .getLayoutParams();
        // // aLayoutParams.setMargins(context.curTabViewIndex*context.length, 0, 0, 0);
        // // context.tab_front_bg.setLayoutParams(aLayoutParams);
        // // // context.tab_front_bg.clearAnimation();//解决移动后闪烁现象 ①
        // // TranslateAnimation anim = new TranslateAnimation(0,0,0,0);　　 ②
        // // context.tab_front_bg.setAnimation(anim);　　　　　　　　　　　　　　 ③
        //
        // r_top.clearAnimation();
        // }
        //
        // @Override
        // public void onAnimationRepeat(Animation animation) {
        // // TODO Auto-generated method stub
        //
        // }
        //
        // @Override
        // public void onAnimationStart(Animation animation) {
        //
        // }
        // });


    }

    private void performAnimate(boolean isHide, int start, int end) {
        if (!isHide) {
            showHideView(false);
        } else {
            showHideView(true);
        }
        ViewWrapper wrapper = new ViewWrapper(r_top);
        ObjectAnimator oa = ObjectAnimator.ofInt(wrapper, "height", start, end);
        oa.setInterpolator(new AccelerateInterpolator());
        oa.setDuration(100);
        oa.start();

    }


    private class ViewWrapper {
        private final View mTarget;

        public ViewWrapper(View target) {
            mTarget = target;
        }

        public int getHeight() {
            return mTarget.getLayoutParams().height;
        }

        public void setHeight(int height) {
            mTarget.getLayoutParams().height = height;
            mTarget.requestLayout();
        }
    }

    private void showHideView(boolean isHide) {
        if (isHide) {
            layout_for_pop.setVisibility(View.INVISIBLE);
            vManage.setVisibility(View.INVISIBLE);
            back.setVisibility(View.INVISIBLE);
            sixin.setVisibility(View.INVISIBLE);
            vAttention.setVisibility(View.INVISIBLE);
            user_icon.setVisibility(View.INVISIBLE);
            user_name.setVisibility(View.INVISIBLE);
            fans_count.setVisibility(View.INVISIBLE);

        } else {

            if (UserState.getUser() == null) {
                vManage.setVisibility(View.GONE);
                // 测试,给版主加上
            } else if (UserState.getUser().adminid == 1 || UserState.getUser().adminid == 2) {
                vManage.setVisibility(View.VISIBLE);
            } else {
                vManage.setVisibility(View.GONE);
            }
            back.setVisibility(View.VISIBLE);
            sixin.setVisibility(View.VISIBLE);
            vAttention.setVisibility(View.VISIBLE);
            user_icon.setVisibility(View.VISIBLE);
            user_name.setVisibility(View.VISIBLE);
            fans_count.setVisibility(View.VISIBLE);
        }

    }
}
